package com.cyz.manager.sharding;

import lombok.extern.slf4j.Slf4j;
import org.apache.shardingsphere.sharding.api.sharding.standard.PreciseShardingValue;
import org.apache.shardingsphere.sharding.api.sharding.standard.RangeShardingValue;
import org.apache.shardingsphere.sharding.api.sharding.standard.StandardShardingAlgorithm;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Properties;

/**
 * 图片表分表算法
 */
@Slf4j
public class PictureShardingAlgorithm implements StandardShardingAlgorithm<Long> {

    /**
     * 精确查询
     * @param collection    所有分表表名集合
     * @param preciseShardingValue  查询参数（内置）
     * @return  要查询的表名
     */
    @Override
    public String doSharding(Collection<String> collection, PreciseShardingValue<Long> preciseShardingValue) {
        // 获取分表参数
        Long spaceId = preciseShardingValue.getValue();
        // 获取逻辑表名
        String logicTableName = preciseShardingValue.getLogicTableName();
        log.info("逻辑表名==============================>{}", logicTableName);

        // 如果表名为空，表示查询所有图片
        if (spaceId == null){
            // 返回逻辑表名表示查询所有分表
            return logicTableName;
        }
        // 拼接表名
        String searchTableName = "picture_" + spaceId;
        // 判断表名是否存在
        if (collection.contains(searchTableName)){
            // 如果存在就返回该表名
            return searchTableName;
        }else {
            // 如果不存在就在 全表中查找 或 报错
            return logicTableName;
        }
    }

    @Override
    public Collection<String> doSharding(Collection<String> collection, RangeShardingValue<Long> rangeShardingValue) {
        return new ArrayList<>();
    }

    @Override
    public Properties getProps() {
        return null;
    }

    @Override
    public void init(Properties properties) {

    }
}
